#include "bdd.h"

row *
del_row (row * head, row * des)
{
  row *ret = head;
  if (!head || !des)
    return head;
  if (des->next)
    des->next->prev = des->prev;

  if (des->prev)
    des->prev->next = des->next;
  else
    ret = des->next;

  free (des->val);
  free (des->ident);
  free (des);
  return (ret);
}

racine *
del_base (racine * head, racine * one)
{
  racine *ret = head;
  if (!head || !one)
    return (ret);

  if (one->next)
    one->next->prev = one->prev;
  if (one->prev)
    one->prev->next = one->next;
  else
    ret = one->next;

  one->base = del_subbase (one->base, one->base);
  free (one);
  return (ret);
}


subbase *
del_subbase (subbase * head, subbase * one)
{
  subbase *ret = head, *run, *tmp_parent, *tmp_next, *par = NULL;
  row *rtmp, *row_next;

  if (!head || !one)
    return (ret);

  if (one->next)
    one->next->prev = one->prev;
  if (one->prev)
    one->prev->next = one->next;
  else
    ret = one->next;

  if (one->parent && one->parent->enfant == one)
    one->parent->enfant = one->next;

  run = one;
  while (1)
    {
      if (run)
	{
	  for (rtmp = run->rows; rtmp; rtmp = row_next)
	    {
	      row_next = rtmp->next;
	      free (rtmp->val);
	      free (rtmp->ident);
	      free (rtmp);
	    }
	  run->rows = NULL;
	  par = run;
	  run = run->enfant;
	}
      else
	{
	  run = par;
	  tmp_next = run->next;
	  tmp_parent = run->parent;
	//  printf ("[1] free subbase : %s\n", run->ident);
	  free (run->ident);
	  free (run);
	  if (run == one)
	    break;

	  if (tmp_next)
	    {
	      run = tmp_next;
	      run->prev = NULL;
	    }
	  else
	    {
	      run = tmp_parent;
	      if (!run)
		break;

	      if (run == one)
		{
		  //printf ("[2] free subbase : %s\n", run->ident);
		  free (run->ident);
		  free (run);
		  break;
		}
	      par = run;
	      tmp_next = run->next;
	      if (tmp_next)
		{
		 // printf ("[3] free subbase : %s\n", run->ident);
		  free (run->ident);
		  free (run);
		  tmp_next->prev = NULL;
		}
	      run = tmp_next;
	    }
	}			/*
				   else
				   break; */
    }
  return (ret);
}

void
free_session (uint si)
{
  free (sess_tab[si]);
  sess_tab[si] = NULL;

  if (si + 1 == sess_top)
    {
      sess_top--;
      sess_tab = realloc (sess_tab, sess_top * sizeof (session *));
    }
}
